﻿using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using IMClient.Config;
using IMClient.Model;
using IMClient.Model.UI;

namespace IMClient.ViewModels
{
    public partial class AddFriendWindowViewModel : ObservableObject
    {
        private readonly HttpClient _httpClient;

        [ObservableProperty] private string searchText = string.Empty;

        [ObservableProperty] private FriendViewModel? searchResult;

        [ObservableProperty] private ObservableCollection<FriendViewModel> friendsList = new(); // 改用 FriendViewModel

        [ObservableProperty] private string errorMessage = string.Empty;

        [ObservableProperty] private bool hasError;

        public AddFriendWindowViewModel()
        {
            _httpClient = new HttpClient
            {
                BaseAddress = new Uri(NetWorkConfig.BaseUrl)
            };
            PropertyChanged += AddFriendWindowViewModel_PropertyChanged;
        }

        private async void AddFriendWindowViewModel_PropertyChanged(object? sender,
            PropertyChangedEventArgs e)
        {
            if (e.PropertyName == nameof(SearchText))
            {
                if (SearchText?.Length == 10)
                {
                    Debug.WriteLine("Triggering search...");
                    await SearchFriend(SearchText);
                }
                else
                {
                    // 清空搜索结果和错误信息
                    FriendsList.Clear();
                    HasError = false;
                    ErrorMessage = "";
                }
            }
        }

        private async Task SearchFriend(string searchText)
        {
            try
            {
                HasError = false;
                ErrorMessage = string.Empty;
                FriendsList.Clear();

                var requestData = new { UserId = searchText };
                var jsonContent = JsonSerializer.Serialize(requestData);
                var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

                var response = await _httpClient.PostAsync("/user/query/userinfo", content);
                var jsonResponse = await response.Content.ReadAsStringAsync();

                var apiResponse = JsonSerializer.Deserialize<ApiResponse>(jsonResponse);

                if (apiResponse == null)
                {
                    HasError = true;
                    ErrorMessage = "服务器响应异常";
                    return;
                }

                switch (apiResponse.Code)
                {
                    case "0000":
                        if (apiResponse.Data != null)
                        {
                            var friend = new FriendViewModel
                            {
                                Id = searchText, // 添加 ID
                                Name = apiResponse.Data.UserName,
                                Avatar = apiResponse.Data.Avatar,
                                IsFriend = false,
                                ButtonText = "添加好友"
                            };
                            FriendsList.Add(friend);
                        }

                        break;

                    case "1102":
                        HasError = true;
                        ErrorMessage = "用户不存在";
                        break;

                    default:
                        HasError = true;
                        ErrorMessage = apiResponse.Message;
                        break;
                }
            }
            catch (Exception ex)
            {
                HasError = true;
                ErrorMessage = $"搜索失败：{ex.Message}";
                Debug.WriteLine($"搜索失败：{ex}");
            }
        }

        [RelayCommand]
        private async Task AddFriend(FriendViewModel friend)
        {
            try
            {
                var requestData = new
                {
                    senderId = User.UserId,
                    senderName = User.UserName,
                    senderAvatar = User.UserAvatar,
                    receiverId = friend.Id,
                    description = "很高兴认识你"
                };

                var jsonContent = JsonSerializer.Serialize(requestData);
                var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

                var response = await _httpClient.PostAsync("/friend/add", content);
                var jsonResponse = await response.Content.ReadAsStringAsync();
                var apiResponse = JsonSerializer.Deserialize<ApiResponse>(jsonResponse);

                if (apiResponse?.Code == "0000")
                {
                    HasError = false;
                    ErrorMessage = string.Empty;
                    friend.IsFriend = true;
                    friend.ButtonText = "已申请";

                    // 更新好友通知
                    var contactsViewModel = ChatWindowViewModel.Instance.GetContactsViewModel();
                    var friendNotificationViewModel = contactsViewModel?.GetFriendNotificationViewModel();
                    
                    friendNotificationViewModel?.AddFriendRequest(new FriendNotification
                    {
                        Name = friend.Name,
                        Avatar = friend.Avatar,
                        SenderId = friend.Id,
                        Action = "好友申请",
                        Time = DateTime.Now.ToString("yyyy/MM/dd"),
                        Message = "我：很高兴认识你",
                        Status = "等待验证",
                        RequestMessageId = String.Empty
                    });
                    contactsViewModel?.CheckFriendNotification();
                }   
                else
                {
                    HasError = true;
                    ErrorMessage = apiResponse?.Message ?? "添加好友失败";
                }
            }
            catch (Exception ex)
            {
                HasError = true;
                ErrorMessage = $"添加好友失败：{ex.Message}";
            }
        }
    }
}